package de.tud.etit.blipz.services.storage;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.content.Context;
import de.tud.etit.blipz.entities.User;
import de.tud.etit.blipz.exceptions.ApplicationException;

public class GlobalStorage {
	private static String credentialFileName;

	private static Context context;

	private static User user;

	public static User getUser() {

		if (GlobalStorage.user == null
				|| GlobalStorage.user.getMobileNr() == null
				|| GlobalStorage.user.getPassword() == null) {
			GlobalStorage.loadUser();
		}

		return user;
	}

	public static void setUser(User user) {
		GlobalStorage.user = user;
		GlobalStorage.persistUser();
	}

	public static String getCredentialFileName() {
		return credentialFileName;
	}

	public static void setCredentialFileName(String credentialFileName) {
		GlobalStorage.credentialFileName = credentialFileName;
	}

	public static Context getContext() {
		return context;
	}

	public static void setContext(Context context) {
		GlobalStorage.context = context;
	}

	private static void persistUser() {
		try {
			if (GlobalStorage.fileExists() == false) {
				return;
			}

			FileOutputStream fos = GlobalStorage.context.openFileOutput(
					credentialFileName, Context.MODE_PRIVATE);
			ObjectOutputStream os = new ObjectOutputStream(fos);
			os.writeObject(GlobalStorage.user);
			os.close();
			fos.close();
		} catch (Exception ex) {
			throw new ApplicationException();
		}
	}

	private static void loadUser() {
		try {
			if (GlobalStorage.fileExists() == false) {
				return;
			}
			
			FileInputStream fis = GlobalStorage.context
					.openFileInput(credentialFileName);
			ObjectInput is = new ObjectInputStream(fis);
			GlobalStorage.user = (User) is.readObject();
			is.close();
			fis.close();
		} catch (EOFException eofException) {
			GlobalStorage.user = new User();
		}
		catch (IOException ioException)
		{
			GlobalStorage.user = new User();
		}
		catch(Exception ex)
		{
			throw new ApplicationException();
		}
	}

	private static boolean fileExists() {
		File file = new File(GlobalStorage.context.getFilesDir(),
				GlobalStorage.credentialFileName);
		return file.exists();
	}
}
